import {Component} from '@angular/core';
import {IonicPage, ModalController, NavController, NavParams} from 'ionic-angular';
import {PagesService} from "../../services/pages.service";
import {UserService} from "../../services/user.service";
import {Pattern} from "../../public/service/pattern";
import {Common} from "../../public/service/common";

@IonicPage()
@Component({
  selector: 'page-setting',
  templateUrl: 'setting.html',
})
export class SettingPage {
  public userInfo: any = {};
  public editConfig = {
    realName: false,
    nickName: false,
    phone: false,
    alipay: false,
    wechat: false,
    idCard: false
  };

  constructor(public navCtrl: NavController, public navParams: NavParams,
              private pagesService: PagesService, public modalCtrl: ModalController,
              private userService: UserService, private common: Common) {
  }


  ionViewDidEnter() {
    this.loadInfo()
  }

  /**
   * 我的个人信息及各种余额信息
   */
  loadInfo() {
    this.userService.loadInfo().then(data => {
      this.userInfo = data;
    })
  }

  updateRealName(name) {
    this.userService.updateRealName(name).then(res => {
      this.editConfig.realName = false;
      this.userInfo.realName = name;
    })
  }

  updateNickName(name) {
    this.userService.updateNickName(name).then(res => {
      this.editConfig.nickName = false;
      this.userInfo.nickName = name;
    })
  }

  updatePhone(value) {
    if (!Pattern.PHONE_REGEXP.test(value)) {
      this.common.toast('手机号码格式不正确');
      return;
    }
    this.userService.updatePhone(value).then(res => {
      this.editConfig.phone = false;
      this.userInfo.phone = value;
    })
  }

  updateIdCard(value) {
    if (!Pattern.IDCARD_REGEXP.test(value)) {
      this.common.toast('身份证格式不正确');
      return;
    }
    this.userService.updateIdCard(value).then(res => {
      this.editConfig.idCard = false;
      this.userInfo.idCard = value;
    })
  }

  updateAlipay(value) {
    this.userService.updateAlipay(value).then(res => {
      this.editConfig.alipay = false;
      this.userInfo.alipay = value;
    })
  }

  updateWechat(value) {
    this.userService.updateWechat(value).then(res => {
      this.editConfig.wechat = false;
      this.userInfo.wechat = value;
    })
  }

  updatePassword() {
    const modal = this.modalCtrl.create('UpPasswordPage', {type: 'password'});
    modal.present();
  }

  updatePinPassword() {
    const modal = this.modalCtrl.create('UpPasswordPage', {type: 'pinPassword'});
    modal.present();
  }

  /**
   * 退出
   */
  logout(event) {
    event.preventDefault();
    this.pagesService.logout().then(res => {
      this.navCtrl.setRoot('LoginPage');
    })
  }

}
